#!/usr/bin/make -f
CC=gcc
INSTALL_MOD_DIR:=extra
KVERSION   ?= $(shell uname -r)
KERNEL_SRC :=  /lib/modules/$(KVERSION)
MOD_SRC_DIR:= $(shell pwd)
KBUILD_OUTPUT=$(KERNEL_SRC)/build

LIB_DIR = usr/lib/python3.7/dist-packages
CUSTOM_RULES_DIR := $(shell pwd)/debian

export  INSTALL_MOD_DIR top_srcdir KVERSION  KERNEL_SRC CC  KBUILD_OUTPUT

currentdir = $(shell pwd)
MODULE_DIRS := b6510-48vs8cq
export CUSTOMS_DIRS MODULE_DIRS

#all product need common
COMPILE_DIRS = $(MODULE_DIRS)

clean_dirs = $(MODULE_DIRS)
clean_dirs += common

custom_clean_dirs := $(addprefix _clean_,$(clean_dirs) )


%:
	dh $@
build: $(COMPILE_DIRS)
	@echo "build success"

$(custom_clean_dirs):
	$(MAKE) -C $(patsubst _clean_%,%,$@) clean

common_build :
	$(MAKE) -C  $(MOD_SRC_DIR)/common

$(COMPILE_DIRS): common_build
	$(MAKE) -C  $(MOD_SRC_DIR)/$@
	dh_testdir
	dh_installdirs
	if [ $@ = "b6510-48vs8cq" ]; then \
            dh_installdirs -pplatform-modules-ruijie-$@ \
                    $(KERNEL_SRC)/$(INSTALL_MOD_DIR); \
        fi; \
	cp -r $(MOD_SRC_DIR)/common/build/*  debian/platform-modules-ruijie-$@/
	cp -r $(MOD_SRC_DIR)/$@/build/*  debian/platform-modules-ruijie-$@/

	@(for mod in $(MODULE_DIRS); do \
		cp -r $@/build/* $(MOD_SRC_DIR)/debian/platform-modules-ruijie-$${mod}/; \
		if [ $$mod = "b6510-48vs8cq" ]; then \
			cd $(MOD_SRC_DIR)/$${mod}; \
			cp -r $(MOD_SRC_DIR)/common/lib/plat_hal $(MOD_SRC_DIR)/$${mod}/; \
			cp -r $(MOD_SRC_DIR)/common/lib/rjutil $(MOD_SRC_DIR)/$${mod}/; \
			cp -r $(MOD_SRC_DIR)/common/lib/eepromutil $(MOD_SRC_DIR)/$${mod}/; \
			python3 setup.py bdist_wheel -d $(MOD_SRC_DIR)/$${mod}/modules; \
			rm -rf $(MOD_SRC_DIR)/$${mod}/plat_hal; \
			rm -rf $(MOD_SRC_DIR)/$${mod}/rjutil; \
			rm -rf $(MOD_SRC_DIR)/$${mod}/eepromutil; \
			cd $(MOD_SRC_DIR); \
		fi; \
	done)

binary: binary-indep
	@echo "======================================================="

binary-indep:
	# Resuming debhelper scripts
	dh_testroot
	dh_install
	dh_installchangelogs
	dh_installdocs
	dh_systemd_enable
	dh_installinit
	dh_systemd_start
	dh_link
	dh_fixperms
	dh_compress
	dh_strip
	dh_installdeb
	dh_gencontrol
	dh_md5sums
	dh_builddeb
override_dh_usrlocal:

override_dh_pysupport:

clean: $(custom_clean_dirs)
	dh_testdir
	dh_testroot
	dh_clean

.PHONY: build  $(COMPILE_DIRS) binary binary-arch binary-indep clean
